package org.itstack.demo.netty.server;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class MyServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, DatagramPacket datagramPacket) throws Exception {
        String msg = datagramPacket.content().toString(Charset.forName("GBK"));
        System.out.println("UDP服务端接收到消息：" + msg);

        // 向客户端发送消息
        String json = "通知：我已收到你的消息\r\n";
        byte[] jsonBytes = json.getBytes(Charset.forName("GBK"));
        DatagramPacket data = new DatagramPacket(Unpooled.copiedBuffer(jsonBytes), datagramPacket.sender());
        channelHandlerContext.writeAndFlush(data); // 向客户端发送消息

    }
}
